package com.xxl.javaWork_15;

import java.io.*;
import java.util.List;

/**
 * @Author: xiaxinlin
 * @Date: 2020/12/23 18:33
 */
public class IOStreamCopyDemo {
    public static void main(String[] args) {
        File file = new File("D:\\img\\test");
        File file1 = new File("D:\\img\\filetest");
        if (file1.getAbsolutePath().startsWith(file.getAbsolutePath()+File.separator)){
            System.out.println("目录文件夹是源文件的子文件夹！！！");
        }else {
            try {
                file1 = new File(file1,file.getName());
                IOStreamCopyDemo.copyDir(file,file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void copyDir(File sourceDir,File daddrDir) throws IOException {
        if (!daddrDir.exists()){
            daddrDir.mkdirs();
        }
        File[] files = sourceDir.listFiles();
        File daddrPath;
        for (File file : files) {
            if (file.isDirectory()){
                daddrPath=new File(daddrDir,file.getName());
                copyDir(file,daddrPath);
            }else {
                daddrPath=new File(daddrDir,file.getName());
                copyFile(file,daddrPath);
            }
        }
    }

    public static void copyFile(File source,File daddr) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(daddr));
        int len;
        byte b[] = new byte[1024];
        while ((len=inputStream.read(b))!=-1){
            outputStream.write(b,0,len);
        }
        inputStream.close();
        outputStream.close();
    }
}
